//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2007
//
// Object properties dialog - 'Extras' page.
//

# include "StdAfx.h"
# include "Resource.h"
# include "RgnProperties.h"
# include "Map.h"
# include "ParseHelpers.h"
# include "SetRgnExtra.h"
# include "ListView.h"
# include "EditText.h"
# include "Settings.h"

const char * CRgnExtrasPage::_GetValue (const char * _pKey, const char * _pEnd) {
	if (_pKey >= _pEnd)
		return _pEnd;
	const char * const p = reinterpret_cast<const char *> (::memchr (_pKey, '=', _pEnd - _pKey));
	return p ? p + 1 : _pEnd;
}

void CRgnExtrasPage::_FillExtras (HWND _hList) {
	ListView_DeleteAllItems (_hList);

	if (m_rgn.pExtra && ! m_rgn.pExtra->strExtra.empty ()) {
		const char * p = m_rgn.pExtra->strExtra.data ();
		const char * const pEnd = p + m_rgn.pExtra->strExtra.size ();
		size_t cItem = 0;
		do {
			const char * const pNextLine = FindNextLine (p, pEnd);

			const char * const pKey = p;
			const char * const pValue = _GetValue (p, pNextLine);

			InsertItem     (_hList, cItem, 0, "%s", string_t (pKey, pValue).c_str ());
			SetSubItemText (_hList, cItem, 1, "%s", string_t (pValue, GetLineLen (pValue, pNextLine)).c_str ());

			p = pNextLine;
			++ cItem;
		} while (p < pEnd);

		::EnableWindow (_hList, TRUE);
	} else
		::EnableWindow (_hList, FALSE);

	AutoSizeColumns (_hList);
}

bool CRgnExtrasPage::OnInit (HWND _hwndFocus) {
	const HWND hExtras = GetDlgItem (IDC_EXTRAS);

	AddColumn (hExtras, 0, "Key");
	AddColumn (hExtras, 1, "Value");

	_FillExtras (hExtras);

	return true;
}

void CRgnExtrasPage::OnCommand (WORD _wCmd, WORD _wNotifyCode, HWND _hwndCtl) {
	string_t strText = m_rgn.pExtra ? m_rgn.pExtra->strExtra : "";
	if (EditText (m_hWnd, strText, "Edit source", true)) {
/*		const size_t cLen = strText.size ();
		if (
			cLen == 1 ||
			strText [cLen - 2] != '\r' ||
			strText [cLen - 1] != '\n'
		)
			strText.append ("\r\n");*/

		SetObjectExtra (m_rgn, strText);

		const HWND hExtras = GetDlgItem (IDC_EXTRAS);
		_FillExtras (hExtras);
	}
}
